package ntut.andengine.game;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture;
import org.anddev.andengine.opengl.texture.bitmap.BitmapTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Intent;

public class GameScene extends BaseGameActivity {

	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 800;
	
	Scene mScene;
	TextureRegion blackTextureRegion;
	Sprite black;
	
	public Scene getScene(){
		return mScene;
	}
	
	@Override
	public Engine onLoadEngine() {
		final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		camera.setZClippingPlanes(-100, 100);
		final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
		engineOptions.getTouchOptions().setRunOnUpdateThread(true);
		engineOptions.setNeedsMusic(true);
		engineOptions.setNeedsSound(true);
		return new Engine(engineOptions);
	}

	@Override
	public void onLoadResources() {
		BitmapTextureRegionFactory.setAssetBasePath("gfx/");
		BitmapTexture bitmapTexture = new BitmapTexture(1, 1, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		blackTextureRegion = BitmapTextureRegionFactory.createFromAsset(bitmapTexture, this, "black.png", 0, 0);		
		mEngine.getTextureManager().loadTexture(bitmapTexture);	
		mScene = new Scene();
		
		black = new Sprite(240, 400, blackTextureRegion);
		black.setScale(CAMERA_WIDTH, CAMERA_HEIGHT);
		black.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
	}

	@Override
	public Scene onLoadScene() {
		return null;
	}

	@Override
	public void onLoadComplete() {
		black.registerEntityModifier(new AlphaModifier(1, 1, 0));
		mScene.attachChild(black);
		this.mEngine.enableVibrator(this);
	}
	
	public void startActivity(GameScene activity, Class<?> nextActivity){

		this.runOnUiThread(new Runnable(){

			@Override
			public void run() {
				black.registerEntityModifier(new AlphaModifier(1, 0, 1));						
			}
        	
        });

		BufferObjectManager.getActiveInstance().clear();
		activity.finish();
		activity.startActivity(new Intent(activity, nextActivity));
		
	}

}
